<?php

namespace app\api\controller;

use app\common\model\Goods as GoodsModel;
use app\common\model\User as UserModel;
use app\store\model\Setting as SettingModel;

use app\common\library\sms\Driver as SmsDriver;
use think\Cache;
use think\Request;

/**
 * 首页控制器
 * Class Index
 * @package app\api\controller
 */
class Index extends Controller
{
    /**
     * 首页
     * @return array
     * @throws \think\exception\DbException
     */
    public function page()
    {
        //获得按钮菜单列表
        $menu_list = thumbImgUrl(db("menu")->where(['status' => 1])->field("title,target_type,target_data,thumb")->order(['sort' => 'DESC','menu_id' => 'DESC'])->select()->toArray());
        //获得广告banner广告图
        $goodsmodel = new GoodsModel;
        //热门产品
        $hot_goods = thumbImgUrl($goodsmodel->pageList(['goods_type' => 1] , 10)->toArray()['data']);
        //兑换产品
        $integral_goods = thumbImgUrl($goodsmodel->pageList(['goods_type' => 2] , 10)->toArray()['data']);
        //获得banner图片
        $index_brand = thumbImgUrl(db("ads")->where(['type' => 'index_banner' , 'status' => 1])->field("title,target_type,target_data,thumb")->order(['sort' => 'DESC','ads_id' => 'DESC'])->select()->toArray());
        //获得热门产品广告图片
        $hot_ads = thumbImgUrl(db("ads")->where(['type' => 'index_center1' , 'status' => 1])->field("title,target_type,target_data,thumb")->order(['sort' => 'DESC','ads_id' => 'DESC'])->select()->toArray());
        //获得积分兑换产品广告图片
        $integral_ads = thumbImgUrl(db("ads")->where(['type' => 'index_center2' , 'status' => 1])->field("title,target_type,target_data,thumb")->order(['sort' => 'DESC','ads_id' => 'DESC'])->select()->toArray());
        return $this->renderSuccess(compact('menu_list' , 'hot_goods' , 'integral_goods' ,'index_brand' , 'hot_ads' , 'integral_ads'));
    }
    
    /**
     * APP启动广告
     */
    public function startupads() {
        $ads_list = thumbImgUrl(db("ads")->where(['type' => 'start_up_list' , 'status' => 1])->field("title,target_type,target_data,thumb")->order(['sort' => 'DESC','ads_id' => 'DESC'])->select()->toArray());
        return $this->renderSuccess(compact('ads_list'));
    }
    
    
    /**
     * 所有地区
     */
    public function area() {
        $area = db("region")->field("id,pid,name,level")->select();
        $new_area = [];
        foreach( $area as $value ) {
            $new_area[$value['pid']][] = $value;
        }
        foreach ( $new_area[0] as $k => $v ) {
            if( isset( $new_area[$v['id']] ) ) {
                $level2 =  $new_area[$v['id']];
                foreach( $level2 as $k1 => $v1 ) {
                    if( isset( $new_area[$v1['id']] ) ) {
                        $level2[$k1]['list'] = $new_area[$v1['id']];
                    }
                }
                $new_area[0][$k]['list'] = $level2;
            }
        }
        $area = $new_area[0];
        return $this->renderSuccess(compact('area'));
    }
    
    /**
     * 获得所有的分类以及二级分类
     */
    public function catelist() {
        $list = thumbImgUrl(db("category")->where(['parent_id' => 0])->field("category_id,name")->order('sort DESC,category_id DESC')->select()->each(function($item , $key){
            $item['list'] = db("category")->where(['parent_id' => $item['category_id']])->field("category_id,name,thumb")->order('sort DESC,category_id DESC')->select()->toArray();
            return $item;
        })->toArray());
        return $this->renderSuccess(compact('list'));
    }
    
    /**
     * 用户登录
     */
    public function login() {
        $mobile = $this->request->param('mobile') ? $this->request->param('mobile') : $this->error('登录手机号不能为空');
        $password = $this->request->param('password') ? $this->request->param('password') : $this->error('登录密码不能为空');
        $cid = $this->request->param('cid') ? $this->request->param('cid') : '';
        $user_info = db("user")->where(['mobile' => $mobile])->find();
        $userModel = new UserModel;
        if( !$user_info || (  $userModel->passmd5($password) != $user_info['password'] ) ) {
            $this->error('用户名或密码错误，请核对');
        }
        if( $user_info['status'] <= 1 ) {
            $this->error('用户被禁用，请联系管理员解除，谢谢配合！');
        }
        $login_save = [
            'login_time' => time(),
            'login_ip' => request()->ip(),
            'login_token' => md5( $mobile . time() ),
			'ge_cid' => $cid
        ];
        //更新登录信息
        db("user")->where(['user_id' => $user_info['user_id']])->update($login_save);
        $result_user = thumbImgUrl([
            'user_id' => $user_info['user_id'],
            'mobile' => $user_info['mobile'],
            'nickname' => $user_info['nickname'],
            'sex' => $user_info['sex'],
            'avatar' => $user_info['avatar'],
            'province_name' => $user_info['province_name'],
            'city_name' => $user_info['city_name'],
            'area_name' => $user_info['area_name'],
            'login_token' => $login_save['login_token']
        ]);
        return $this->renderSuccess(compact('result_user'));
    }
    
    /**
     * 用户注册
     */
    public function register() {
        $mobile = $this->request->param('mobile') ? $this->request->param('mobile') : $this->error('手机号不能为空');
        $password = $this->request->param('password') ? $this->request->param('password') : $this->error('登录密码不能为空');
        $code = $this->request->param('code') ? $this->request->param('code') : $this->error('短信验证码不能为空');
		$nickname = $this->request->param("nickname/s" , '');
		if( !$nickname ) $this->error("请输入您的姓名");
		$province = $this->request->param("province/d" , 0);
		if( $province <= 0 ) $this->error("请选择省份");
		$city = $this->request->param("city/d" , 0);
		if( $city <= 0 ) $this->error("请选择城市");
		$area = $this->request->param("area/d" , 0);
		if( $area <= 0 ) $this->error("请选择区域");
		if( !preg_match('/^1[3-9][0-9]{9}$/is' , $mobile) ) {
			$this->error('手机号格式错误，请重新输入');
		}
		//$fx_user_id = $this->request->param("user_id/d" , 0);
        if( db("user")->where(['mobile' => $mobile])->find() ) {
            $this->error('手机号码已存在，请更换');
        }
		$config_data = SettingModel::getItem('store');
		$share_code = $this->request->param("share_code/d" , 0);
		if( $share_code > 0 ) {
			$rec_user_info = db("user")->where(["share_code" => $share_code,'status' => 2])->find();
			if( !$rec_user_info ) {
				$this->error("推荐码有误，请核对");
			}
			$fx_user_id = $rec_user_info['user_id'];
		} else {
			$fx_user_id = isset($config_data['manage_user_id'])?$config_data['manage_user_id']:0;
		}
        //验证短信
        if( Cache::get($mobile . '_mobile_checked_1') != $code ) {
            $this->error('验证码错误，请核对');
        }
        //删除缓存
        Cache::rm($mobile . '_mobile_checked_1');
        //判断是否赠送积分
		$integral = $config_data['integral'] > 0 ? $config_data['integral'] : 0;
		$userModel = new UserModel;
		$share = db("user")->order("share_code DESC")->value("share_code");
        $result = db("user")->insert([
            'mobile' => $mobile , 
            'password' => $userModel->passmd5($password),
            'nickname' => '未设置',
            'avatar' => '/assets/default/default.jpg',
			'province' => $province,
			'city' => $city,
			'area' => $area,
			'integral' => $integral,
			'nickname' => $nickname,
			'total_integral' => $integral,
			'province_name' => db('region')->where(['id' => $province])->value("name"),
			'city_name' => db('region')->where(['id' => $city])->value("name"),
			'area_name' => db('region')->where(['id' => $area])->value("name"),
			'parent_id' => $fx_user_id,
			'share_code' => ( $share ? $share : 1000000 ) + rand(20 , 50),
            'create_time' => time()
        ]);
		$user_id = db("user")->getLastInsID();
		//赠送积分写入日志
		if( $integral > 0 ) {
			db("user_integral_log")->insert([
				'user_id' => $user_id,
				'num' => $integral,
				'type' => 1,
				'content' => '注册新用户平台赠送积分【'.$integral.'】',
				'create_time' => time()
			]);
		}
		//获得普通用户推荐奖励
		$obj = new UserModel();
		$obj->ordinaryuserRec( $user_id );
        if( $result ) {
            $this->success('注册成功');
        } else {
            $this->error('注册失败');
        }
    }
    
    /**
     * 密码找回
     */
    public function savepass() {
        $mobile = $this->request->param('mobile') ? $this->request->param('mobile') : $this->error('手机号不能为空');
        $password = $this->request->param('password') ? $this->request->param('password') : $this->error('新登录密码不能为空');
        $code = $this->request->param('code') ? $this->request->param('code') : $this->error('短信验证码不能为空');
        if( !$user_info = db("user")->where(['mobile' => $mobile])->find() ) {
            $this->error('手机号码不存在，请核对');
        }
        //验证短信
        if( Cache::get($mobile . '_mobile_checked_2') != $code ) {
            $this->error('验证码错误，请核对');
        }
        //删除缓存
        Cache::rm($mobile . '_mobile_checked_2');
        $userModel = new UserModel;
        $result = db("user")->where(['user_id' => $user_info['user_id']])->update(['password' => $userModel->passmd5($password)]);
        $this->success('密码修改成功');
    }
	
	/**
	 * 获得列表
	 */
	public function goodslist() {
		$goodstype = $this->request->param("goodstype/d",1);
		$goodstype = $goodstype == 1 ? 1 : 2;
		$cat_id = $this->request->param("cat_id/d",0);
		$sort_price = $this->request->param("sort_price/s",'');
		$sort_num = $this->request->param("sort_num/s",'');
		$keyword = $this->request->param("key/s" , '');
		$where = ['goods_type' => $goodstype];
		//分类筛选
		if($cat_id>0){
			$where['category_data'] = ['LIKE' , '%,'.$cat_id.',%'];
		}
		//搜索
		if( $keyword != '' ) {
			$where['goods_name'] = ['LIKE' , '%'.htmlspecialchars($keyword).'%'];
		}
		$goodsModel = new GoodsModel;
		$orderby = $sort_price||$sort_num?($sort_price?['price',$sort_price]:['sales',$sort_num]):'all'; //排序
		$list = thumbImgUrl($goodsModel->pageList( $where , 10 , $orderby)->toArray()['data']);
		return $this->renderSuccess(compact('list'));
	}
    
	/**
	 * 热门搜索
	 */
	public function hotsearch() {
		$data = SettingModel::getItem('store');
		$list = isset( $data['hot_search'] ) && $data['hot_search'] ? explode(",",$data['hot_search']) : [];
		return $this->renderSuccess(compact('list'));
	}
	
    /**
     * 发送短信验证码
     */
    public function sendSms() {
        $mobile = $this->request->param('mobile') ? $this->request->param('mobile') : $this->error('手机号不能为空');
        $type = in_array($this->request->param('type') , array(1,2,3,4)) ? $this->request->param('type') : $this->error('请求类型错误');
        switch( $type ) {
            case 1 : //手机注册
			case 4 : //更换手机号
                if( db("user")->where(['mobile' => $mobile])->find() ) {
                    $this->error('手机号码已存在，请更换');
                }
                break;
            case 2 : //找回密码
			case 3 : //设置支付密码
                if( !db("user")->where(['mobile' => $mobile])->find() ) {
                    $this->error('手机号码不存在，请核对');
                }
                break;
        }
        $rand = rand(100000 , 999999);
		//发送短信验
		$sms_info = SettingModel::getItem('sms');
		$SmsDriver = new SmsDriver([
            'default' => 'aliyun',
            'engine' => [
                'aliyun' => [
                    'AccessKeyId' => $sms_info['engine']['aliyun']['AccessKeyId'],
                    'AccessKeySecret' => $sms_info['engine']['aliyun']['AccessKeySecret'],
                    'sign' => $sms_info['engine']['aliyun']['sign'],
                    'order_pay' => [
						'is_enable' => 1,
						'template_code' => 'SMS_143595052',
						'accept_phone' => $mobile
					],
                ],
            ],
        ]);
        $templateParams = ['code' => $rand];
        if ($SmsDriver->sendSms('order_pay', $templateParams, true)) {
			Cache::set($mobile . '_mobile_checked_' . $type , $rand , 3600);//写入缓存
            $this->success('短信发送成功' , $rand);
        }
        $this->error('短信发送失败');
    }
	
	/**
	 * 商品详情
	 */
	public function goodsinfo() {
		$goodsid = $this->request->param("goodsid/d" , 0);
		if( $goodsid <= 0 ) $this->error('商品数据不存在');
		$goodsinfo = db("goods")->where(['goods_id' => $goodsid,'is_delete' => 0 , 'goods_status' => 10])->find();
		if( !$goodsinfo ) $this->error('商品数据不存在');
		//获取商品规格类型
		if( $goodsinfo['spec_type'] == 10 ) { //单品规格
			$specinfo = db("goods_spec")->where(['goods_id' => $goodsid])->find();
			$goods = [
				'price' => $specinfo['goods_price'],
				'marketprice' => $specinfo['line_price'],
				'stock_num' => $specinfo['stock_num'],
				'weight' => $specinfo['goods_weight'],
				'sku' => $specinfo['goods_no'],
				'attr_price' => [],
				'attr_list' => [],
			];
		} else { //多个规格
			$specinfo = db("goods_spec")->where(['goods_id' => $goodsid])->order("goods_price ASC")->select()->toArray();
			$goods = [
				'price' => $specinfo[0]['goods_price'],
				'marketprice' => $specinfo[count($specinfo) - 1]['line_price'],
				'stock_num' => array_sum(array_column($specinfo , 'stock_num')),
				'weight' => $specinfo[0]['goods_weight'],
				'sku' => $specinfo[0]['goods_no']
			];
			$attr_data = [];
			//获得属性价
			foreach( $specinfo as $k => $v ) {
				$goods['attr_price'][] = ['attr_id' => $v['spec_sku_id'] , 'stock_num' => $v['stock_num'] ,'goods_spec_id' => $v['goods_spec_id'] ,'price' => $v['goods_price']];
				$attr_data = array_unique( array_merge( $attr_data , explode("_" , $v['spec_sku_id']) ) );
			}
			//获得属性列表
			sort($attr_data);
			$attr_list = db("spec_value")->where("spec_value_id IN(".implode("," , $attr_data).")")->select()->toArray();
			$attr_spec_ids = array_unique( array_column($attr_list , 'spec_id') );
			//获得属性组列表
			$attr_group_data = db("spec")->where("spec_id IN(".implode("," , $attr_spec_ids).")")->field("spec_id,spec_name AS name")->select()->toArray();
			foreach($attr_group_data as $k => &$v) {
				foreach( $attr_list as $v1 ) {
					if( $v1['spec_id'] == $v['spec_id'] ) {
						$v['list'][] = ['id' => $v1['spec_value_id'] , 'name' => $v1['spec_value']];
					}
				}
			}
			$goods['attr_list'] = $attr_group_data;
		}
		
		//合并二位数据
		$goods = array_merge( $goods , [
			'goods_id' => $goodsinfo['goods_id'],
			'goods_name' => $goodsinfo['goods_name'],
			'spec_type' => $goodsinfo['spec_type'],
			'content' => htmlspecialchars_decode($goodsinfo['content']),
			'goods_image' => thumbImgUrl( $goodsinfo['goods_image']?json_decode($goodsinfo['goods_image'],true):[] ),
			'thumb' => thumbImgUrl( $goodsinfo['thumb'] ),
			'sales' => $goodsinfo['sales_initial'] + $goodsinfo['sales_actual'],
			'goods_type' => $goodsinfo['goods_type'],
			'goods_type_price' => $goodsinfo['goods_type_price'],
			'goods_integral' => $goodsinfo['goods_integral'],
			'is_collect' => 0,
		]);
		//判断是否已收藏
		if( isset( $this->user_info['user_id'] ) && $this->user_info['user_id'] > 0 ) {
			if( db("goods_collection")->where(['goods_id' => $goodsid , 'user_id' => $this->user_info['user_id']])->find() ) {
				$goods['is_collect'] = 1;
			}
		}
		return $this->renderSuccess(compact('goods'));
	}
	
	/**
	 * 商品评论列表
	 */
	public function goodscomment() {
		$goodsid = $this->request->param("goodsid/d" , 0);
		if( $goodsid <= 0 ) $this->error('商品数据不存在');
		$list = thumbImgUrl(db("goods_comment")->alias('gc')->join("yoshop_user u" , 'u.user_id = gc.user_id')->where(['gc.goods_id' => $goodsid , 'gc.status' => 2])
				->field("gc.star,gc.type,gc.content,gc.thumb_list,gc.create_time,u.nickname,u.avatar")->order("gc.comment_id desc")->paginate(5, false, [
            'query' => Request::instance()->request()
        ])->each(function($item,$key){
			$item['create_time'] = date("Y-m-d H:i:s" , $item['create_time']);
			$item['thumb_list'] = $item['thumb_list'] ? json_decode( $item['thumb_list'] , true ) : [];
			return $item;
		})->toArray()['data']);
		return $this->renderSuccess(compact('list'));
	}

	/**
	 * 图片上传
	 */
	public function upload(){
        $file = request()->file('files');  
        if(empty($file)) {  
            $this->error('请选择上传文件');  
        }  
        $info = $file->move(WEB_PATH.DS.'uploads'); 
        $filename = $info->getSaveName();
        if($filename){              
            $this->success('文件上传成功！' , ['file_path' => thumbImgUrl('/uploads/'.$filename),'path' => '/uploads/'.$filename]);  
        }else{
            $this->error($file->getError());  
        }
	}
	
	public function defaultshare() {
		$share_code = '';
		$config = SettingModel::getItem('store');
		if( isset( $config['manage_user_id'] ) && $config['manage_user_id'] ) {
			$share_code = '推荐码,可为空';//db("user")->where(['user_id' => $config['manage_user_id']])->value("share_code");
		}
		$this->success('success' , $share_code);  
	}
	
	/**
	 * 关于我们
	 */
	public function about() {
		$data = SettingModel::getItem('store');
		$this->success("success" , $data['content']);
	}
	
	/**
	 * 车辆品牌 /型号
	 */
	public function brandlist() {
		$list = db("auto_brand")->where(['status' => 1])->field("id,title")->order("id ASC")->select()->each(function($item , $key){
			$item['list'] = db("auto_type")->where(['status' => 1 , 'auto_brand_id' => $item['id']])->field("id,title")->order("id asc")->select()->toArray();
			return $item;
		})->toArray();
		$this->success("success" , $list);
	}
	
	/**
	 * 帮助中心
	 */
	public function help() {
		$result = db("article")->where(['status' => 1])->field("title,content")->order("article_id desc")->select()->toArray();
		$this->success("success" , $result);
	}
	
	/**
	 * 版本号
	 */
	public function version(){
		$config_data = SettingModel::getItem('store');
		$this->success("success" , ['open' => $config_data['open'],'version' => $config_data['version'] , 'url' => 'http://'.$_SERVER['SERVER_NAME'].'/index.php?s=/index/index/version']);
	}
	
}









